import Cocoa

//var str = "Hello, playground"


//多态和类型转换
//定义一个 MediaItem 基类
class MediaItem {
    var name: String
    init(name: String) {
        self.name = name
    }
}

//定义一个子类 Movie
class Movie: MediaItem {
    var director: String
    init(name: String, director: String) {
        self.director = director
        super.init(name: name)
    }
}

//定义一个子类Song
class Song: MediaItem {
    var artist:String
    init(name: String, artist: String) {
        self.artist = artist;
        super.init(name: name)
    }
}

let array = [
    Movie(name: "泰坦尼克号", director: "Jack"),
    Song(name: "我心永恒", artist: "朱丽叶"),
    Movie(name: "英雄儿女", director: "王成"),
    Song(name: "我的祖国", artist: "彭丽媛")
]
//输出数组的类型
print(type(of: array))  //如果数组中是由多个子类构成的话,那么类型只能显示他们共同的基类: MediaItem

//可以遍历数组使用as?向下做类型转换,转换成独有的子类类型
for item in array {
//    switch item {  //这里不能使用is来做类型转换
//    case is Movie:
//        print("movie")
//    case is Song:
//        print("song")

    if let realItem = item as? Movie{
        print(realItem.director)
}
}
